package org.timeismoney.payment.web.action.teacher;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.timeismoney.payment.common.Constants;
import org.timeismoney.payment.exception.BizException;
import org.timeismoney.payment.exception.SysException;
import org.timeismoney.payment.model.Student;
import org.timeismoney.payment.model.StudentDTO;
import org.timeismoney.payment.model.Unit;
import org.timeismoney.payment.model.UnitLevel;
import org.timeismoney.payment.service.StudentService;
import org.timeismoney.payment.service.UnitService;
import org.timeismoney.payment.web.ExcelUtil;
import org.timeismoney.payment.web.WebUtils;
import org.timeismoney.payment.web.action.BaseAction;
import org.timeismoney.payment.web.form.UploadForm;

public class UploadAction extends BaseAction {
	private static Logger		log	= Logger.getLogger(UploadAction.class);
	private UnitService			unitService;
	private StudentService		studentService;

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setUnitService(UnitService unitService) {
		this.unitService = unitService;
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		InputStream is = null;
		List<Student> uploadList = null;
		try {
			UploadForm uploadForm = (UploadForm) form;
			FormFile file = uploadForm.getFile();
			log.info("File upload:" + file.getFileName() + " "
					+ file.getFileSize());
			int unitNo = uploadForm.getUnitNo();
			if (unitNo == 0) {
				throw new BizException("参数错误");
			}
			if (("application/vnd.ms-excel".equals(file.getContentType()) || "application/octet-stream"
					.equals(file.getContentType())) && file.getFileSize() > 0) {
				is = file.getInputStream();
				uploadList = ExcelUtil.readExcel(is);
				is.close();
			}
			if (uploadList == null) {
				throw new BizException("请检查上传文件的格式，以及确保文件未被Excel占用.");
			} else {
				Unit unit = unitService.get(unitNo);
				List<Student> stus = studentService.findStuByUnit(unitNo);
				if (stus != null) {
					for (int i = 0; i < uploadList.size(); i++) {
						Student tmp = uploadList.get(i);
						tmp.setUnit(unit);
						if(stus.contains(tmp)){
							uploadList.remove(tmp);
							i--;
						}
					}
				}
				if (uploadList.size() == 0) {
					throw new BizException("忽略重复学号,文件无有效学生记录");
				}
				studentService.batchInsertStudents(uploadList);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			request.setAttribute("errorMsg", WebUtils.generateErrorJSON("上传失败：" + e.getMessage()));
		} finally{
			if (is != null) {
				is.close();
			}
		}
		return mapping.findForward(SUCCESS);
	}
	
	//add by chamdenjo@gmail.com
	public ActionForward uploadUnit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		InputStream is = null;
		List<String[]> uploadList = null;
		try {
			UploadForm uploadForm = (UploadForm) form;
			FormFile file = uploadForm.getFile();
			log.info("File upload:" + file.getFileName() + " "
					+ file.getFileSize());
			
			if (("application/vnd.ms-excel".equals(file.getContentType()) || "application/octet-stream"
					.equals(file.getContentType())) && file.getFileSize() > 0) {
				is = file.getInputStream();
				uploadList = ExcelUtil.readExcelForUnit(is);
				is.close();
			}
			if (uploadList == null) {
				throw new BizException("请检查上传文件的格式，以及确保文件未被Excel占用.");
			} else {
				
				if (uploadList.size() == 0) {
					throw new BizException("请检查数据,表格中没有符合规范的数据！！");
				}
				unitService.batchInsertUnit(uploadList);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			request.setAttribute("errorMsg", WebUtils.generateErrorJSON("上传失败：" + e.getMessage()));
		} finally{
			if (is != null) {
				is.close();
			}
		}
		return mapping.findForward("success_unit");
	}

	public ActionForward batchUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		InputStream is = null;
		List<Student> uploadList = null;
		try {
			UploadForm uploadForm = (UploadForm) form;
			FormFile file = uploadForm.getFile();
			log.info("File upload:" + file.getFileName() + " "
					+ file.getFileSize());
			if (("application/vnd.ms-excel".equals(file.getContentType()) || "application/octet-stream"
					.equals(file.getContentType())) && file.getFileSize() > 0) {
				is = file.getInputStream();
				uploadList = ExcelUtil.readExcel(is);
				is.close();
			}
			if (uploadList == null) {
				throw new SysException("请检查上传文件的格式，以及确保文件未被Excel占用.");
			} else {
				@SuppressWarnings("unchecked")
				List<UnitLevel> uls = (List<UnitLevel>) request.getSession().getAttribute(Constants.ATTR_KEY_UNIT_LEVELS);
				UnitLevel lowLevel = uls.get(uls.size()-1);
				List<Unit> units = unitService.getUnitsByUnitLevel(lowLevel);
				List<Student> validStus = new ArrayList<Student>();
				List<StudentDTO> invalidStus = new ArrayList<StudentDTO>(); 
				Map<Integer, Unit> unitNoUnitMapping = new HashMap<Integer, Unit>();
				for (Unit unit : units) {
					unitNoUnitMapping.put(unit.getUnitNo(), unit);
				}
				for (Student student : uploadList) {
					StudentDTO stu = (StudentDTO) student;
					if(stu.getUnit()==null){
						stu.setErrorMsg("错误：请输入所属班级#");
						invalidStus.add(stu);
						continue;
					}
					
					if(!unitNoUnitMapping.containsKey(stu.getUnit().getUnitNo())){
						stu.setErrorMsg("错误：班级#"+stu.getUnit().getUnitNo()+"不存在或不为班级");
						invalidStus.add(stu);
						continue;
					}
					validStus.add(stu);
				}
				
				if(invalidStus.size()!=0){
					throw new BizException(WebUtils.generateJSONByCollection(invalidStus));
				}
				
				if(validStus.size()!=0){
					studentService.batchInsertStudents(validStus);
				}
			}
		} catch (BizException e) {
			log.error(e.getMessage(), e);
			request.setAttribute("errorMsg", e.getMessage());
		} catch (SysException e) {
			log.error(e.getMessage(), e);
			request.setAttribute("errorMsg", WebUtils.generateErrorJSON("上传失败：" + e.getMessage()));
		} finally{
			if (is != null) {
				is.close();
			}
		}
		return mapping.findForward(ERROR);
	}
}
